<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class App extends Backend
{
    
    /**
     * App模型对象
     * @var \app\admin\model\App
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\App;
        //栏目列表
        $cate_tree=$this->model->getCateNameList();


        //类型列表
        $type_tree=\db("app_type")
            ->where(["status"=>1])
            ->order("id","asc")
            ->select();

        $this->assign("cate_tree",$cate_tree);
        $this->assign("type_tree",$type_tree);
    }

    //create function by bai
    //获取栏目名称列表--ps:修改,新增的api需要这个
    public function get_cate_name_list(){
        if($this->request->isAjax()){
            //获取栏目列表,PS:这个是common模块下的app模型里面的方法.
            $list=$this->model->getCateNameList();

            $total=count($list);

            //将一维数组,转为下拉框需要的数组
            $arr=[];
            foreach ($list as $k=>$v){
                $arr[]=[
                    "pid"=>$k,
                    "name"=>$v
                ];
            }

            $result = array("total" => $total, "rows" => $arr);
            return json($result);
        }

        return false;

    }

    //create function by bai
    //压缩字符串
    public function gz_str($str){
        $json_content=json_encode($str,JSON_UNESCAPED_UNICODE);//转成json
        $gzip_content=gzcompress($json_content);
        $base64_content=base64_encode($gzip_content);

        return $base64_content;
    }

    //create function by bai
    //解压字符串
    public function gz_un_str($str){
        if(strlen($str)>0){
            $gzip_content=base64_decode($str);
            $json_content=gzuncompress($gzip_content);
            $str_content=json_decode($json_content,true,1024,JSON_BIGINT_AS_STRING);
        }else{
            $str_content="";
        }

        return $str_content;
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                //update by bai
                //压缩文章
                $gz_content=$this->gz_str($params['content']);
                $params['content']=$gz_content;
                //压缩评论html
                $gz_comments=$this->gz_str($params['comments']);
                $params['comments']=$gz_comments;

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }



    /**
     * 编辑
     */
    public function edit($ids = null)
    {

        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }



        //update by bai
        //在这将读取出来的content字段,进行base64转码,在gzip解压,再json转成html字符串
        $str_content=$this->gz_un_str($row['content']);
        //解码comments 评论
        $str_comments=$this->gz_un_str($row['comments']);


        //赋值
        $row["content"]=$str_content;
        $row['comments']=$str_comments;

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");

            //update by bai
            //转json,压缩字符串,base64转码.
            //目的:压缩大小.
            $base64_content=$this->gz_str($params["content"]);
            $params["content"]=$base64_content;
            //压缩评论内容
            $base64_comments=$this->gz_str($params['comments']);
            $params['comments']=$base64_comments;


            if ($params) {

                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    

}
